#include "lottie_widget.h"

#include <QQmlContext>
#include <QUrl>
#include <QVariant>
#include <QQmlEngine>
#include <QQuickItem>
#include <QFileInfo>

#include <settings/qls_settings.h>

LottieWidget::LottieWidget(QWidget *parent) : QQuickWidget(parent)
{
    // 设置 QML 引擎
    setResizeMode(QQuickWidget::SizeRootObjectToView);
    engine()->addImportPath("qrc:/");

    // 加载 QML 文件
    setSource(QUrl("qrc:/animation.qml"));

    // 获取 LottieView 对象
    lottie_animation_ = rootObject()->findChild<QQuickItem *>();

    qDebug() << __FUNCTION__ << lottie_animation_
             << lottie_animation_->objectName();
}

LottieWidget::~LottieWidget()
{
    // 清理资源
}

void LottieWidget::loadLottie(const QString &json_file_path)
{
    if (!lottie_animation_) {
        return;
    }

    QFileInfo file_info(json_file_path);
    if (!file_info.exists() || !file_info.isFile()) {
        return;
    }

    qDebug() << __FUNCTION__ << file_info.absoluteFilePath();
#if 1
    lottie_animation_->setProperty("source", file_info.absoluteFilePath());
#else
    QFile file(file_info.absoluteFilePath());
    if (file.open(QIODevice::ReadOnly)) {
        QByteArray data = file.readAll();
        lottie_animation_->setProperty("source", QVariant::fromValue(data));
        file.close();
    } else {
        qDebug() << "Failed to open animation file: " << json_file_path;
    }
#endif
}

void LottieWidget::startAnimation()
{
    if (lottie_animation_) {
        QMetaObject::invokeMethod(lottie_animation_, "play");
    }
}

void LottieWidget::stopAnimation()
{
    if (lottie_animation_) {
        QMetaObject::invokeMethod(lottie_animation_, "stop");
    }
}
